package com.yeedingtong.config;

import java.io.IOException;

import cn.kivensoft.util.MyLogger;
import jdbm.RecordManager;
import jdbm.helper.FastIterator;
import jdbm.helper.MRU;
import jdbm.htree.HTree;
import jdbm.recman.BaseRecordManager;
import jdbm.recman.CacheRecordManager;

public class Jdbm {
	private final String SERVICE_NAME = "service";
	
	RecordManager recman;
	HTree<String, String> services;
	
	private static Jdbm _instance = new Jdbm();
	public static Jdbm instance() {
		return _instance;
	}
	
	public boolean open(JdbmConfig config) {
		try {
			recman = new BaseRecordManager(config.getJdbmFile());
			
			if (config.getJdbmDisableTransactions())
				((BaseRecordManager)recman).disableTransactions();
			MRU<Long, ?> cache = new MRU<>(config.getJdbmCacheSize());
			recman = new CacheRecordManager(recman, cache);
			
			long recid = recman.getNamedObject(SERVICE_NAME);
			if (recid == 0) {
				services = HTree.createInstance(recman);
				recman.setNamedObject(SERVICE_NAME, services.getRecid());
			}
			else
				services = HTree.load(recman, recid);

			return true;
		} catch (Exception e) {
			MyLogger.error(e);
			return false;
		}
	}
	
	public void close() {
		try {
			recman.close();
		} catch (IOException e) {
			MyLogger.error(e);
		}
	}
	
	public String get(String key) {
		try {
			return services.get(key);
		} catch (IOException e) {
			MyLogger.error(e);
			return null;
		}
	}
	
	public void put(String key, String value) {
		try {
			services.put(key, value);
			recman.commit();
		} catch (IOException e) {
			MyLogger.error(e);
		}
	}
	
	public void remove(String key) {
		try {
			services.remove(key);
			recman.commit();
		} catch (IOException e) {
			MyLogger.error(e);
		}
	}
	
	public FastIterator<String> keys() {
		try {
			return services.keys();
		} catch (IOException e) {
			MyLogger.error(e);
			return null;
		}
	}
	
}
